using BlazorAuth.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BlazorAuth.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    [HttpPost("login")]
    public ActionResult<LoginResponseModel> Login([FromBody] LoginModel loginModel)
    {
        if (loginModel.UserName == "Admin" && loginModel.Password == "Admin")
        {
            var token = GenerateJwtToken(loginModel.UserName);
            return Ok(new LoginResponseModel() {  Token = token });
        }

        return null;
    }

    private string GenerateJwtToken(string userName)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, userName),
            new Claim(ClaimTypes.Role,"Admin")
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Symmetric Security Key_Symmetric Security Key"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "BlazorAuth",
            audience: "BlazorAuth",
            claims: claims,
            expires: DateTime.UtcNow.AddHours(1),
            signingCredentials: creds
            );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
